package com.jlastu.znb.firendcircle;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.jlastu.znb.R;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView friendCircleListView;
    private FriendCircleAdapter adapter;
    private static final int PICK_IMAGE_REQUEST = 1; // 图片选择的请求码
    private ImageView imagePreview; // 在MainActivity类中声明
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nyq);

        friendCircleListView = findViewById(R.id.friend_circle_list);
        List<Item> items = new ArrayList<>();
        adapter = new FriendCircleAdapter(this, items);
        friendCircleListView.setAdapter(adapter);

        Button postButton = findViewById(R.id.post_button);
        postButton.setOnClickListener(view -> showPostDialog());
    }

    private void showPostDialog() {
        LayoutInflater inflater = getLayoutInflater();
        View postView = inflater.inflate(R.layout.post_activity, null);
        final EditText postContentEdit = postView.findViewById(R.id.post_content_edit);
        imagePreview = postView.findViewById(R.id.image_preview);
        Button pickImageButton = postView.findViewById(R.id.pick_image_button);
        Button postConfirmButton = postView.findViewById(R.id.post_confirm_button);

        pickImageButton.setOnClickListener(view -> openImagePicker());

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this)
                .setView(postView)
                .setTitle("发布动态");

        final AlertDialog dialog = builder.create(); // 创建对话框并保存引用

        postConfirmButton.setOnClickListener(view -> {
            String content = postContentEdit.getText().toString().trim();
            if (!content.isEmpty() && imageUri != null) {
                adapter.add(new Item(content, imageUri.toString()));
                Toast.makeText(MainActivity.this, "动态发布成功", Toast.LENGTH_SHORT).show();
                dialog.dismiss(); // 使用保存的对话框引用来关闭对话框
            } else {
                Toast.makeText(MainActivity.this, "请输入动态内容并选择图片", Toast.LENGTH_SHORT).show();
            }
        });

        dialog.show(); // 显示对话框
    }

    private void openImagePicker() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_IMAGE_REQUEST);
        } else {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, PICK_IMAGE_REQUEST);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PICK_IMAGE_REQUEST && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            openImagePicker();
        } else {
            Toast.makeText(this, "需要存储权限来选择图片", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            imageUri = data.getData();
            imagePreview.setImageURI(imageUri);
        }
    }

    public static class Item {
        String content;
        String imageUri;

        public Item(String content, String imageUri) {
            this.content = content;
            this.imageUri = imageUri;
        }
    }

    public class FriendCircleAdapter extends ArrayAdapter<Item> {

        public FriendCircleAdapter(@NonNull Context context, List<Item> items) {
            super(context, 0, items);
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.friend_circle_item, parent, false);
            }

            Item item = getItem(position);
            if (item != null) {
                // 设置文本内容
                TextView textView = convertView.findViewById(R.id.friend_circle_text);
                textView.setText(item.content);
                // 设置图片
                ImageView imageView = convertView.findViewById(R.id.friend_circle_image);
                Glide.with(MainActivity.this).load(Uri.parse(item.imageUri)).into(imageView);
            }
            return convertView;
        }
    }

    private Uri imageUri; // 用于存储选中图片的Uri
}